package com.liliudong.keelflower.upms.biz.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.keelflower.common.core.utils.CacheUtils;
import com.liliudong.keelflower.upms.biz.dao.sys.SysRoleDao;
import com.liliudong.keelflower.upms.biz.entity.sys.SysRole;
import com.liliudong.keelflower.upms.biz.service.sys.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色 服务实现类
 * </p>
 *
 * @author liudong.li
 * @since 2021-06-07
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    private final RedisTemplate<String, SysRole> sysRoleRedisTemplate;

    @Override
    public Set<String> getRoleCodesByUserId(Long sysUserId) {
        List<SysRole> userRoleEntitiesByUserId = this.getRolesByUserId(sysUserId);
        if (ArrayUtil.isNotEmpty(userRoleEntitiesByUserId)) {
            return userRoleEntitiesByUserId.stream()
                    .map(SysRole::getRoleCode)
                    .collect(Collectors.toSet());
        }
        return null;
    }

    @Override
    public List<SysRole> getRolesByUserId(Long sysUserId) {
        String userRedisKey = CacheUtils.SysUser.user(sysUserId);
        HashOperations<String, String, List<SysRole>> hashOperations = sysRoleRedisTemplate.opsForHash();
        List<SysRole> sysRoles = hashOperations.get(userRedisKey, CacheUtils.SysUser.ROLES);
        if (CollectionUtil.isEmpty(sysRoles)) {
            sysRoles = baseMapper.selectListByUserId(sysUserId);
            if (CollectionUtil.isNotEmpty(sysRoles)) {
                hashOperations.put(userRedisKey, CacheUtils.SysUser.ROLES, sysRoles);
            }
        }
        return sysRoles;
    }
}
